<?php
// withdraw.php
session_start();
require 'db_connect.php';

// 验证学生登录
if (!isset($_SESSION['isLoggedIn']) || !$_SESSION['isLoggedIn'] || $_SESSION['role'] !== 'student') {
    http_response_code(401);
    die(json_encode(['success' => false, 'error' => '未授权访问']));
}

// 获取请求数据
$input = json_decode(file_get_contents('php://input'), true);
$offeringID = isset($input['offeringID']) ? intval($input['offeringID']) : 0;
$studentID = $_SESSION['userId'] ?? 0;

if ($offeringID <= 0 || $studentID <= 0) {
    http_response_code(400);
    die(json_encode(['success' => false, 'error' => '参数错误']));
}

try {
    $conn->begin_transaction();

    // 检查是否有成绩
    $checkGradeStmt = $conn->prepare("
        SELECT Grade 
        FROM Enrollment 
        WHERE StudentID = ? AND OfferingID = ?
        FOR UPDATE
    ");
    $checkGradeStmt->bind_param("ii", $studentID, $offeringID);
    $checkGradeStmt->execute();
    $gradeResult = $checkGradeStmt->get_result()->fetch_assoc();

    if (!$gradeResult) {
        throw new Exception("未找到选课记录");
    }

    if (!is_null($gradeResult['Grade'])) {
        throw new Exception("已有成绩不可退课");
    }

    // 执行退课操作
    $deleteStmt = $conn->prepare("
        DELETE FROM Enrollment 
        WHERE StudentID = ? AND OfferingID = ?
    ");
    $deleteStmt->bind_param("ii", $studentID, $offeringID);
    $deleteStmt->execute();

    $conn->commit();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    $conn->rollback();
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}